package com.ahwei.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author：ahwei163@qq.com
 *
 * @date: 202*-03-05 18:29:59
 * @description: 这是一个Java文件！
 */
public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
    private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
    /**
     * 返回sessionFactory对象 工厂对象
     *
     * @return sessionFactory
     */
    private static SqlSessionFactory getSessionFactory() {
        return sqlSessionFactory;
    }
    /**
     * 新建session会话，并把session放在线程变量中
     */
    private static void newSession() {
        // 打开一个session会话
        SqlSession session = getSessionFactory().openSession();
        // 将session会话保存在本线程变量中
        threadLocal.set(session);
    }
    /**
     * 返回session对象
     * @return session
     */
    public static SqlSession getSqlSession(){
        //优先从线程变量中取session对象
        SqlSession session = threadLocal.get();
        //如果线程变量中的session为null，
        if(session==null){
            //新建session会话，并把session放在线程变量中
            newSession();
            //再次从线程变量中取session对象
            session = threadLocal.get();
        }
        return session;
    }
    /**
     * 返回session对象
     * @return session
     */
    public static SqlSession getSqlSession(boolean flag){
        return getSessionFactory().openSession(flag);
    }

    /**
     * 关闭session对象，并从线程变量中删除
     */
    public static void closeSession(){
        //读取出线程变量中session对象
        SqlSession session = threadLocal.get();
        //如果session对象不为空，关闭session对象，并清空线程变量
        if(session != null){
            session.close();
            threadLocal.set(null);
        }
    }
}
